package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.BaseContext;
import com.itheima.exception.CustomException;
import com.itheima.mapper.AddressBookMapper;
import com.itheima.mapper.OrdersMapper;
import com.itheima.mapper.ShoppingCartMapper;
import com.itheima.pojo.*;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrdersService;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    UserService userService;

    @Override
    public void submit(Orders orders) {
        //获取当前登录人的id
        Long currentId = BaseContext.getCurrentId();

        //查询购物车里面是否存在数据
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShoppingCart::getUserId, currentId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(lambdaQueryWrapper);
        //判断数据是否存在 , 如果不存在说明数据库没有数据
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new CustomException("购物车没有物品");
        }
        //获取地址id 查询地址是否存在
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookMapper.selectById(addressBookId);
        if (addressBook == null) {
            throw new CustomException("地址错误");
        }
        //user 表里信息
        User user = userService.getById(currentId);

        //用雪花生成订单表id
        long id = IdWorker.getId();

        //通过提供执行方法的控制进行值的原子操作  0 为默认值 默认从0开始
        AtomicInteger atomicInteger = new AtomicInteger(0);

        //创建集合将购物车的数据放进点单明显表中
        //组装订单明细信息
        List<OrderDetail> details = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            //设置订单号
            orderDetail.setOrderId(id);
            //设置订单名字
            orderDetail.setName(item.getName());
            //订单图片
            orderDetail.setImage(item.getImage());
            //dish_id
            orderDetail.setDishId(item.getDishId());
            //setmeal_id
            orderDetail.setSetmealId(item.getSetmealId());
            //dish_flavor
            orderDetail.setDishFlavor(item.getDishFlavor());
            //number
            orderDetail.setNumber(item.getNumber());
            //amount 第一次循环为0+菜品价格
            orderDetail.setAmount(item.getAmount());
            //计算0+菜品价格
            //使用函数将这次的个数和价格相乘,getAmount=0
            atomicInteger.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        //将设置的值整体存入订单明细表
        orderDetailService.saveBatch(details);

        //组装订单数据
        //id值
        orders.setId(id);
        //设置订单时间
        orders.setOrderTime(LocalDateTime.now());
        //设置checkout time
        orders.setCheckoutTime(LocalDateTime.now());
        //设置支付方式
        orders.setStatus(2);
        //设置总金额
        orders.setAmount(new BigDecimal(atomicInteger.get()));
        //设置用户id
        orders.setUserId(currentId);
        //设置number  String类型的订单id
        orders.setNumber(String.valueOf(id));
        //设置consignee 从addresss表中拿到consignee
        orders.setConsignee(addressBook.getConsignee());
        //设置user_name,从用户表中获取
        orders.setUserName(userService.getById(currentId).getName());
        orders.setUserName(user.getName());
        //设置电话, 从用户表中获取
        orders.setPhone(userService.getById(currentId).getPhone());
        //设置地址表中查询数据 拼接 某某省+某某市......
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));


        //将orders数据添加到订单表中
        ordersMapper.insert(orders);

        //下单完成后需要删除购物车里面的所有数据
        shoppingCartMapper.delete(lambdaQueryWrapper);


    }
}
